package api.business;


import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import common.BaseController;
import common.CommonResult;
import common.validateUser.InterfaceUsers;
import common.validateUser.ValidateUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import services.business.BusinessInfoServices;
import services.company.CompanyInfoServices;
import services.dictionary.ItemTypeServices;
import services.dictionary.MajorTypeServices;
import services.staff.StaffInfoServices;
import services.upms.AccountServices;
import services.upms.PermissionRoleServices;
import util.DateUtil;
import util.cryptogram.MD5Util;
import util.key.IDFactory;
import validator.NotBlankFluentValidator;
import validator.NotNullFluentValidator;
import wt.entity.business.BusinessInfo;
import wt.entity.company.CompanyInfo;
import wt.entity.dictionary.ItemType;
import wt.entity.dictionary.MajorTypeExample;
import wt.entity.staff.StaffInfo;
import wt.entity.upms.Account;
import wt.staticData.ShortData;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/8/16.
 */
@Controller
@RequestMapping("httpApi")
public class AddBusinessInfoController extends BaseController {
    @Autowired
    public InterfaceUsers interfaceUsers;
    @Autowired
    ItemTypeServices itemTypeServices;
    @Autowired
    BusinessInfoServices businessInfoServices;
    @Autowired
    StaffInfoServices staffInfoServices;
    @Autowired
    MajorTypeServices majorTypeServices;
    @Autowired
    CompanyInfoServices companyInfoServices;
    @Autowired
    AccountServices accountServices;
    @Autowired
    PermissionRoleServices permissionRoleServices;


    /**
     * 添加业务信息
     *
     * @param uid
     * @param timeStamp
     * @param sign
     * @param businessCode
     * @param companyName
     * @param companyCode
     * @param address
     * @param productName
     * @param businessType
     * @param applicationTime
     * @param acceptTime
     * @param itemNum
     * @param managerUserId
     * @param observerUserId
     * @param majorNumList
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "addBusinessInfo", produces = "application/json;charset=UTF-8")
    public CommonResult addBusinessInfo(
            String uid,
            Long timeStamp,
            String sign,
            String businessCode,
            String companyName,
            String companyCode,
            String address,
            String productName,
            String businessType,
            @DateTimeFormat(pattern = DateUtil.DATE_TIME_PATTEN) Date applicationTime,
            @DateTimeFormat(pattern = DateUtil.DATE_TIME_PATTEN) Date acceptTime,
            String itemNum,
            String managerUserId,
            String observerUserId,
            String majorNumList
    ) throws Exception {

        ComplexResult result = FluentValidator.checkAll().failOver()
                .on(uid, new NotBlankFluentValidator("uid"))
                .on(timeStamp, new NotNullFluentValidator("timeStamp"))
                .on(sign, new NotBlankFluentValidator("sign"))
                .on(businessCode, new NotBlankFluentValidator("businessCode"))
                .on(companyName, new NotBlankFluentValidator("companyName"))
                .on(companyCode, new NotBlankFluentValidator("companyCode"))
                .on(address, new NotBlankFluentValidator("address"))
                .on(businessType, new NotBlankFluentValidator("businessType"))
                .on(applicationTime, new NotNullFluentValidator("applicationTime"))
                .on(acceptTime, new NotNullFluentValidator("acceptTime"))
                .on(itemNum, new NotNullFluentValidator("itemNum"))
                .on(managerUserId, new NotBlankFluentValidator("managerUserId"))
//                .on(observerUserId, new NotBlankFluentValidator("observerUserId"))
                .on(majorNumList, new NotBlankFluentValidator("majorNumList"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            CommonResult commonResult = new CommonResult();
            commonResult.addMessage(result);
            commonResult.setCode(CommonResult.ZJ005);
            return commonResult;
        }


        CommonResult commonResult = ValidateUserUtil.validateUser(uid, timeStamp, sign, interfaceUsers);  //用户验证
        if (!CommonResult.ZJ001.equals(commonResult.getCode())) {
            return commonResult;
        }

//        businessType = BusinessType.getValue(businessType);
//        if (businessType == null) {
//            commonResult.setMessage(CommonResult.ZJ005_M + "businessType");
//            commonResult.setCode(CommonResult.ZJ005);
//            return commonResult;
//        }


        if (null != businessInfoServices.selectByBusinessCode(businessCode)) {//businessCode 已存在时，返回错误
            commonResult.setMessage(CommonResult.ZJ005_M + "businessCode");
            commonResult.setCode(CommonResult.ZJ005);
            return commonResult;
        }
        ItemType itemType = itemTypeServices.selectByItemNum(itemNum);
        if (itemType == null) {
            commonResult.setMessage(CommonResult.ZJ005_M + "itemNum");
            commonResult.setCode(CommonResult.ZJ005);
            return commonResult;
        }

        StaffInfo observer = null;
        if (!StringUtils.isBlank(observerUserId)) {
            observer = staffInfoServices.selectByUserId(observerUserId);
            if (observer == null) {
                commonResult.setMessage(CommonResult.ZJ005_M + "observer");
                commonResult.setCode("zj005");
                return commonResult;
            }

//            alter table bus_business_info modify  (observer_id  varchar2(32)  null);
//            alter table bus_business_info modify  (observer_name  varchar2(128)  null);
        }

        StaffInfo manager = staffInfoServices.selectByUserId(managerUserId);
        if (manager == null) {
            commonResult.setMessage(CommonResult.ZJ005_M + "manager");
            commonResult.setCode("zj005");
            return commonResult;
        }

        BusinessInfo businessInfo = new BusinessInfo();
        businessInfo.setBusinessCode(businessCode);
        businessInfo.setCompanyName(companyName);
        businessInfo.setCompanyCode(companyCode);
        businessInfo.setAddress(address);
        businessInfo.setProductName(productName);
        businessInfo.setBusinessType(businessType);
        businessInfo.setApplicationTime(applicationTime);
        businessInfo.setAcceptTime(acceptTime);

        businessInfo.setItemId(itemType.getId());
        businessInfo.setItemNum(itemType.getNum());
        businessInfo.setItemName(itemType.getName());

        if (observer!=null){
            businessInfo.setObserverId(observer.getId());
            businessInfo.setObserverName(observer.getName());
        }

        businessInfo.setManagerId(manager.getId());
        businessInfo.setManagerName(manager.getName());

        businessInfo.setBusinessWorkFlow(ShortData.s0);
        businessInfo.setInspectorAssessCount(0);
        businessInfo.setInspectorCount(0);
        businessInfo.setCompanyIsAssess(ShortData.s0);
        businessInfo.setObserverIsAssess(ShortData.s0);
        businessInfo.setObserverIsReport(ShortData.s0);
        businessInfo.setManagerIsAssess(ShortData.s0);
        businessInfo.setFundStatus(ShortData.s0);
        businessInfo.setCreateObject(uid);
        businessInfo.setCreateTime(new Date());

        List<String> majorNumListHandle = Arrays.asList(majorNumList.trim().split(","));
        MajorTypeExample majorTypeExample = new MajorTypeExample();
        majorTypeExample.createCriteria().andNumIn(majorNumListHandle);
        int count = majorTypeServices.countByExample(majorTypeExample);
        if (count != majorNumListHandle.size()) {
            commonResult.setMessage(CommonResult.ZJ005_M + "majorNumList");
            commonResult.setCode(CommonResult.ZJ005);
            return commonResult;
        }


        CompanyInfo companyInfo = companyInfoServices.selectByCompanyCode(businessInfo.getCompanyCode());
        if (companyInfo == null) {
            companyInfo = new CompanyInfo();
            companyInfo.setId(IDFactory.getSnowflakeId());
            companyInfo.setName(businessInfo.getCompanyName());
            companyInfo.setCompanyCode(businessInfo.getCompanyCode());
            Account account = new Account();
            account.setRoleId("369000000000004093");
            account.setLoginName(companyInfo.getCompanyCode());
            account.setPassword(MD5Util.md5Hex(companyInfo.getCompanyCode()));
            account.setCompanyId(companyInfo.getId());
            accountServices.insertSelective(account, account.getRoleId(), companyInfo);
        }
        businessInfo.setCompanyId(companyInfo.getId());
        businessInfoServices.insertSelective(businessInfo, majorNumListHandle);
        commonResult.setMessage(CommonResult.ZJ001_M);
        commonResult.setCode(CommonResult.ZJ001);
        return commonResult;

    }


}
